from flask import request, current_app
from flask_restx import Resource, Namespace, fields
from app.services.user_review_service import UserReviewService
from app.utils.auth import admin_required
from app.utils.response import success_response, error_response
from app.utils.validators import validate_required_fields
from . import api

# 创建命名空间
user_review_ns = Namespace('user-review', description='用户审核管理')

# 定义请求模型
review_user_model = user_review_ns.model('ReviewUser', {
    'status': fields.Integer(required=True, description='审核结果：1通过3不通过'),
    'reason': fields.String(description='审核不通过原因')
})

batch_review_model = user_review_ns.model('BatchReview', {
    'user_ids': fields.List(fields.Integer, required=True, description='用户ID列表'),
    'status': fields.Integer(required=True, description='审核结果：1通过3不通过'),
    'reason': fields.String(description='审核不通过原因')
})

@user_review_ns.route('/pending')
class PendingUsersAPI(Resource):
    """待审核用户列表"""
    
    @admin_required
    def get(self, current_admin):
        """获取待审核用户列表"""
        try:
            page = request.args.get('page', 1, type=int)
            per_page = request.args.get('per_page', 20, type=int)
            keyword = request.args.get('keyword', '')
            
            # 获取待审核用户列表
            users, total = UserReviewService.get_pending_users(page, per_page, keyword)
            
            return success_response({
                'users': [user.to_dict() for user in users],
                'total': total,
                'page': page,
                'per_page': per_page,
                'total_pages': (total + per_page - 1) // per_page
            }, '获取成功')
        except Exception as e:
            current_app.logger.error(f"获取待审核用户列表异常: {str(e)}")
            return error_response(f"获取失败: {str(e)}", 500)


@user_review_ns.route('/<int:user_id>')
class UserReviewAPI(Resource):
    """单个用户审核"""
    
    @user_review_ns.expect(review_user_model)
    @admin_required
    def put(self, user_id, current_admin):
        """审核用户"""
        try:
            # 验证必填字段
            is_valid, error_msg = validate_required_fields(['status'])
            if not is_valid:
                return error_response(error_msg, 400)
            
            data = request.get_json()
            status = data.get('status')
            reason = data.get('reason', '')
            
            # 状态验证
            if status not in [1, 3]:
                return error_response('状态值无效，只能是1(通过)或3(不通过)', 400)
            
            # 审核不通过时必须提供原因
            if status == 3 and not reason:
                return error_response('审核不通过时必须提供原因', 400)
            
            # 执行审核
            result = UserReviewService.review_user(user_id, status, reason, current_admin.id)
            if not result:
                return error_response('用户不存在或审核失败', 404)
            
            status_text = '通过' if status == 1 else '不通过'
            return success_response(result, f'用户审核{status_text}成功')
        except Exception as e:
            current_app.logger.error(f"审核用户异常: {str(e)}")
            return error_response(f"审核失败: {str(e)}", 500)


@user_review_ns.route('/batch')
class BatchUserReviewAPI(Resource):
    """批量用户审核"""
    
    @user_review_ns.expect(batch_review_model)
    @admin_required
    def put(self, current_admin):
        """批量审核用户"""
        try:
            # 验证必填字段
            is_valid, error_msg = validate_required_fields(['user_ids', 'status'])
            if not is_valid:
                return error_response(error_msg, 400)
            
            data = request.get_json()
            user_ids = data.get('user_ids', [])
            status = data.get('status')
            reason = data.get('reason', '')
            
            # 参数验证
            if not user_ids:
                return error_response('用户ID列表不能为空', 400)
            
            if status not in [1, 3]:
                return error_response('状态值无效，只能是1(通过)或3(不通过)', 400)
            
            if status == 3 and not reason:
                return error_response('审核不通过时必须提供原因', 400)
            
            # 执行批量审核
            success_count, failed_count = UserReviewService.batch_review_users(
                user_ids, status, reason, current_admin.id
            )
            
            status_text = '通过' if status == 1 else '不通过'
            return success_response({
                'success_count': success_count,
                'failed_count': failed_count,
                'total_count': len(user_ids)
            }, f'批量审核完成，成功{success_count}个，失败{failed_count}个')
        except Exception as e:
            current_app.logger.error(f"批量审核用户异常: {str(e)}")
            return error_response(f"批量审核失败: {str(e)}", 500)


@user_review_ns.route('/<int:user_id>/detail')
class UserReviewDetailAPI(Resource):
    """用户审核详情"""
    
    @admin_required
    def get(self, user_id, current_admin):
        """获取用户详细信息用于审核"""
        try:
            user_detail = UserReviewService.get_user_review_detail(user_id)
            if not user_detail:
                return error_response('用户不存在', 404)
            
            return success_response(user_detail, '获取成功')
        except Exception as e:
            current_app.logger.error(f"获取用户审核详情异常: {str(e)}")
            return error_response(f"获取失败: {str(e)}", 500)


@user_review_ns.route('/statistics')
class ReviewStatisticsAPI(Resource):
    """审核统计"""
    
    @admin_required
    def get(self, current_admin):
        """获取审核统计数据"""
        try:
            stats = UserReviewService.get_review_statistics()
            return success_response(stats, '获取成功')
        except Exception as e:
            current_app.logger.error(f"获取审核统计异常: {str(e)}")
            return error_response(f"获取失败: {str(e)}", 500)


# 将命名空间注册到API实例
api.add_namespace(user_review_ns) 